﻿using log4net;
using MySql.Data.MySqlClient;
using server.Model;
using server.Tool;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Utils;
using System.Linq;

namespace server.DAO
{
    public class LifeDao:CommonDao
    {

        ILog Logger = log4net.LogManager.GetLogger("server.DAO.LifeDao");

        private int GetRoomIdByUser(int userId)
        {
            string sql = "select room_id from room_user where user_id = @user_id";
            List<object> result = MySqlExecuteTools.GetSingleFieldResult(sql, new MySqlParameter[] { new MySqlParameter("@user_id", userId) });
           // Console.WriteLine(sql);
            if (result.Count > 0)
            {
                int roomId = int.Parse(result[0].ToString());

                return roomId;
            }
            return -1;

        }

        public string GetRoomLifeInfoByUser(string userId)
        {
            //只考虑玩家
            int roomId = GetRoomIdByUser(int.Parse(userId));

            string sql = "select user_id from room_user where room_id = @roomId";
            //获取用户列表
            List<object> list = MySqlExecuteTools.GetSingleFieldResult(sql, new MySqlParameter[] { new MySqlParameter("@roomId", roomId) });


            if (list.Count > 0)
            {
                List<string> resultStr = new List<string>();
                list.ForEach((id) =>
                {

                    resultStr.Add(id.ToString());
                });
                string result = StrUtil.ConnetString(resultStr, ",");
                sql = "select * from life where userId in  (" + result + ")";
                List<Life> lifes = MySqlExecuteTools.GetObjectResult<Life>(sql, null);
                lifes.ForEach((life) =>
                {

                    life.userName = MySqlExecuteTools.GetSingleFieldResult("select name from user  where id = @id", new MySqlParameter[] { new MySqlParameter("@id", life.userId) })[0].ToString();


                });

                return Utils.CollectionsConvert.ToJSON(lifes);
            }
            else
            {
                return "";
            }
        }

        public string GetPlayerInfoByUser(string userId)
        {
          
            Life life = GetLifeById(userId);
            if(life!=null)
            {
                life.userName = MySqlExecuteTools.GetSingleFieldResult("select name from user  where id = @id",
                new MySqlParameter[] { new MySqlParameter("@id", life.userId) })[0].ToString();

                string json = Utils.CollectionsConvert.ToJSON(life);
                return json;
            }
            else

            {
                return "-1";
            }
           
        }

        private Life GetLifeById(string userId)
        {
            string sql = "select * from life where userId =@userId";
            List<Life> lifes = MySqlExecuteTools.GetObjectResult<Life>(sql, new MySqlParameter[] { new MySqlParameter("@userId", int.Parse(userId)) });
            if (lifes != null && lifes.Count > 0)
            {
                return lifes[0];
            }

            return null;
        }
        /// <summary>
        /// 玩家之间转让命值和弹量
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="addLifeValue"></param>
        /// <param name="addBulletCount"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public string TransferPlayerLifeBulletCount(string userId, 
            string addLifeValue, string addBulletCount, string currentUser)
        {
            //Console.WriteLine("userId="+ userId + ",addLifeValue=" + addLifeValue +
            //    ",addBulletCount=" + addBulletCount + ",currentUser=" + currentUser);
            string sql = "select * from life  where userId = @userId";
            Life currrentlife = MySqlExecuteTools.GetObjectResult<Life>(sql,
               new MySqlParameter[] { new MySqlParameter("@userId", currentUser) })[0];
            //命值和胆量不足
            if (currrentlife.lifeValue < int.Parse(addLifeValue))
            {
                return "1";
            }
            if (currrentlife.bulletCount < int.Parse(addBulletCount))
            {
                return "1";
            }
            ///输送给命值的用户
            Life targetAddlife = MySqlExecuteTools.GetObjectResult<Life>(sql,
               new MySqlParameter[] { new MySqlParameter("@userId", userId) })[0];

            //Console.WriteLine(targetAddlife.lifeValue+","+ addLifeValue);
            //推送命值复活
            if(targetAddlife.lifeValue==0 && int.Parse(addLifeValue) > 0)
            {

                PublishAddData(userId);
            }

            //弹量增加信息推送
            if(targetAddlife.bulletCount == 0 && int.Parse(addBulletCount) > 0)
            {
                PublishAddData(userId,false);
            }

            //当前用户减少
            sql = "update life set lifeValue = '" + (targetAddlife.lifeValue + int.Parse(addLifeValue)) +
                "', bulletCount = '" + (targetAddlife.bulletCount + int.Parse(addBulletCount)) + "' where userId = " + userId;
            MySqlExecuteTools.GetCountResult(sql);

            //目标减少
            sql = "update life set lifeValue = '" + (currrentlife.lifeValue - int.Parse(addLifeValue)) + "', bulletCount = '"
                + (currrentlife.bulletCount - int.Parse(addBulletCount)) + "' where userId = " + currentUser;
            MySqlExecuteTools.AddOrUpdate(sql);
            return "0";
        }

      



        /// <summary>
        /// 若命值复活或者子弹耗尽后增加了，推送客户端提示
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isLife"></param>
        private void PublishAddData(string userId,bool isLife =true)
        {
           string  sql = "select r.name from room_user ru  left join room r on r.id = ru.room_id where ru.user_id =  " + userId;
            List<object> roomNameResult = MySqlExecuteTools.GetSingleFieldResult(sql, null);

            UserItem userNameItem = MySqlExtendTools.GetEntityObjectByPrimaryKey<UserItem>(userId, "user");

            if (roomNameResult.Count > 0 && userNameItem != null)
            {
                //命值
                if(isLife)
                {
                    PublishDeathData(userNameItem.name, userId, roomNameResult[0].ToString(), false);
                }
                else
                {

                    PublishBulletData(userNameItem.name, userId, roomNameResult[0].ToString(), false);
                }
                
            }
        }

        public string SearchBlueToothState(string userID)
        {
            Grounp grounpByPlayer = GetGrounpByPlayer(int.Parse(userID));
           
            if (grounpByPlayer ==null || (grounpByPlayer!=null && grounpByPlayer.runState == -1))
            {
                return  "6EBB";
            }

            if (grounpByPlayer.playerTime * 60 - grounpByPlayer.remainTime <= grounpByPlayer.fireTime * 60)
            {
                return  "6EBB";
            }

            string sql = "select * from life  where userId = @userId";
            Life life = MySqlExecuteTools.GetObjectResult<Life>(sql, new MySqlParameter[]
            {
                new MySqlParameter("@userId", userID)
            }).FirstOrDefault<Life>();

            if (life!=null)
            {

                if (life.lifeValue == 0 && life.bulletCount > 0)
                {
                    return "6EDD";
                }
                else if (life.lifeValue > 0 && life.bulletCount == 0)
                {
                    return "6ECC";
                }

                else if (life.lifeValue == 0 && life.bulletCount == 0)
                {

                    return "6EBB";

                }
            
            }
            return "6EAA";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="GrounpId"></param>
        /// <returns></returns>
        public bool SearchUserScoreFinishByGrounp(string GrounpId)
        {
            string sql = " select ur.user_id from grounp g, room r,room_user ur where  g.id = r.grounpId and r.id =  ur.room_id  and g.id = " + GrounpId;

            List<object> objUserIdList = MySqlExecuteTools.GetSingleFieldResult(sql, null);
            List<string> userIds = new List<string>();
            objUserIdList.ForEach((item) =>
            {
                userIds.Add(item.ToString());
            });

            string result = StrUtil.ConnetString(userIds, ",");
            sql = "select * from life where  (bulletCount<=0 or lifeValue<=0) and userId in (" + result + ")";

            int count = MySqlExecuteTools.GetCountResult(sql, null);

            if (count > 0)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="lifeValue"></param>
        /// <param name="bulletCount"></param>
        /// <param name="fightScore"></param>
        /// <param name="notificationMesage">是否消息推送</param>
        /// <returns></returns>UpdatePlayerDataBlueTooth
        public void UpdatePlayerDataBlueTooth(string userId, string userName,string lifeValue, 
            string bulletCount, string fightScore,string notificationMesage)
        {

            userId = userId.Trim();
            userName = userName.Trim();
            lifeValue = lifeValue.Trim();
            bulletCount = bulletCount.Trim();
            fightScore = fightScore.Trim();
            notificationMesage = notificationMesage.Trim();

            //Console.WriteLine("lifeValue="+ lifeValue+ ",bulletCount="+ bulletCount+ ",fightScore=" + fightScore);
            //判断是否加入游戏
            Grounp grounp = GetGrounpByPlayer(int.Parse(userId));
            if(grounp == null)
            {
                return;
            }
            string sql = "";
            //打中减命
            if (lifeValue.Equals("-99999"))
            {
                sql = "select hitReduceLifeValue from grounp_life  where grounp_id = @grounp_id";
                List<object> list = MySqlExecuteTools.GetSingleFieldResult(sql,
                   new MySqlParameter[] { new MySqlParameter("@grounp_id", grounp.id) });

                if(list.Count>0)
                {
                    lifeValue = list[0].ToString();
                    lifeValue =  (Convert.ToInt16( lifeValue) * -1).ToString();
                }
                else
                {
                    lifeValue = "-1";
                }

                //被击中的人
                PublishEffectionNotice(userId, userName,true);


            }
            Life life = GetLifeById(userId);
           
            int _lifeValue = life.lifeValue + int.Parse(lifeValue);

            bool playerDeath = false;
            //玩家已阵亡，推送阵亡的信息
            if (life.lifeValue > 0 && int.Parse(lifeValue) < 0 && _lifeValue <= 0)
            {
               playerDeath = true;
            }

            if (_lifeValue<0)
            {
                _lifeValue = 0;
            }


            //子弹已用完提示
            int _bulletCount = life.bulletCount + int.Parse(bulletCount);
            bool bulletFinish = false;
            if (life.bulletCount > 0 && int.Parse(bulletCount) < 0 && _bulletCount <= 0)
            {
                bulletFinish = true;
            }


            if (_bulletCount<0)
            {
                _bulletCount = 0;
            }
            int _fightScore = life.fightScore + int.Parse(fightScore);
            if(_fightScore<0)
            {
                _fightScore = 0;
            }

           sql = "update life set lifeValue = '" + _lifeValue +
                "', bulletCount = '" + _bulletCount + "', fightScore = '" + _fightScore + "' where userId = " + userId;

           
            MySqlExecuteTools.AddOrUpdate(sql);

            sql = "select r.name from room_user ru left join room r on r.id = ru.room_id where ru.user_id =  " + userId;
            List<object> result = MySqlExecuteTools.GetSingleFieldResult(sql, null);
            if (result.Count > 0 )
            {
                //战绩大于0说明是好枪法的人
                if(int.Parse(fightScore) > 0 && notificationMesage.Equals("0"))
                {
                    PublishEffectionNotice(userId, userName,false);
                }
               
                //阵亡
                if(playerDeath)
                {
                    PublishDeathData(userName, userId, result[0].ToString());
                }
                //子弹用完
                if(bulletFinish)
                {
                    PublishBulletData(userName, userId, result[0].ToString());
                }
            }
            else
            {
              //  Console.WriteLine("无需推送：" + result.Count + "," +
                   // "sql=" + sql + ",bulletCount=" + bulletCount);
            }
            //快速更新
            MapDataPushHandle.Instance.RealPushMapData();

        }

       /// <summary>
       /// 在地图上显示击中
       /// </summary>
       /// <param name="userId"></param>
       /// <param name="isHit">true 为被几倍</param>
        private void PublishEffectionNotice(string userId, string userName, bool isHit)
        {
            string roomName = GetRoomNameByUerId(userId);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic["userId"] = userId;
            dic["userName"] = userName;
            dic["roomName"] = roomName;
            dic["isHit"] = isHit;
            PublishPlayerList(userId, dic);
            
        }

        /// <summary>
        /// 阵亡命值提示
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userId"></param>
        /// <param name="roomName"></param>
        public void PublishDeathData(string userName, string userId, string roomName, bool playerDeath = true)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("userName", userName);
            dic.Add("roomName", roomName);
            dic.Add("userId", userId);
            dic.Add("playerDeath", playerDeath);
            PublishPlayerList(userId, dic);
        }

        //弹量提示
        public void PublishBulletData(string userName, string userId, string roomName,bool bulletUseFinish = true)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("userName", userName);
            dic.Add("roomName", roomName);
            dic.Add("userId", userId);
            dic.Add("bulletFinish", bulletUseFinish);
            PublishPlayerList(userId, dic);
        }


        /// <summary>
        /// 推送列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="playerBlueToothItem"></param>
        private void PublishPlayerList(string userId, object itemData)
        {
            SendNoticeMessageInGrounp(userId, itemData, "ShowMapEffection");
        }


        /// <summary>
        /// 增加或减少命值
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="SubTractValue"></param>
        /// <param name="isSub">是否减少</param>
        public void SetLifeValue(string userId, int SubTractValue, bool isSub = true)
        {

            string sql = "select * from life where userId = @userId";
            List<Life> lifes = MySqlExecuteTools.GetObjectResult<Life>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
            if (lifes.Count > 0)
            {
                Life life = lifes.FirstOrDefault<Life>();
                if (life != null)
                {
                    sql = "select r.name from room_user ru  left join room r on r.id = ru.room_id where ru.user_id =  " + userId;
                    List<object> roomNameResult = MySqlExecuteTools.GetSingleFieldResult(sql, null);

                    UserItem userItem = MySqlExtendTools.GetEntityObjectByPrimaryKey<UserItem>(userId, "user");

                    //减少
                    if (isSub)
                    {
                        int subValue = life.lifeValue - SubTractValue;

                        //死亡提示
                        if (life.lifeValue>0 && subValue<=0)
                        {
                            PublishDeathData(userItem.name, userId, roomNameResult[0].ToString(), true);
                        }

                        if (subValue < 0)
                        {
                            subValue = 0;
                        }
                        sql = "update  life set lifeValue  =" + (subValue) + " where id = @id";

                    }
                    //增加
                    else
                    {
                        sql = "update  life set lifeValue  =" + (life.lifeValue + SubTractValue) + " where id = @id;";

                        //复活提示
                        if(life.lifeValue<=0)
                        {
                            PublishDeathData(userItem.name, userId, roomNameResult[0].ToString(), false);
                        }
                    }

                    MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@id", life.id) });
                }

            }
            else
            {
                Console.WriteLine(sql + " :is null");
            }

        }

        /// <summary>
        /// 金币复位
        /// </summary>
        /// <param name="userId"></param>
        public void ResetGlobCoin(int userId)
        {
           string  sql = "update life set goldCoin  = 0  where userId = " + userId;
           MySqlExecuteTools.AddOrUpdate(sql);
        }

        internal string GetGoldCoinList(string roomId)
        {
           string sql = "select * from room_user where room_id = @room_id";
            List<Room_User> room_UserList = MySqlExecuteTools.GetObjectResult<Room_User>(sql,
                new MySqlParameter[] { new MySqlParameter("@room_id", roomId) });

            if(room_UserList == null || room_UserList.Count==0)
            {
                return "";
            }

            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            room_UserList.ForEach((item) => {

                Dictionary<string, object> dic = new Dictionary<string, object>();
                UserItem userItem = MySqlExtendTools.GetEntityObjectByPrimaryKey<UserItem>(item.user_id.ToString(), "user");
                dic.Add("id", userItem.id);
                dic.Add("name", userItem.name);
                sql = "select * from life where userId = @userId";
                List<Life> lifes = MySqlExecuteTools.GetObjectResult<Life>(sql, new MySqlParameter[] { new MySqlParameter("@userId", item.user_id) });
                if (lifes.Count > 0)
                {
                    Life life = lifes.FirstOrDefault<Life>();
                    dic.Add("goldCoinCount", life.goldCoin);
                }
                list.Add(dic);

            });

            return Utils.CollectionsConvert.ToJSON(list);

        }


        internal  string PayGoldCoin(string userId, string count)
        {
            int _count = int.Parse(count);
            string sql = "select * from life where userId = @userId";
            List<Life> lifes = MySqlExecuteTools.GetObjectResult<Life>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
            if (lifes.Count > 0)
            {
                Life life = lifes.FirstOrDefault<Life>();

                if(life.goldCoin - _count > 0)
                {
                    sql = "update  life set goldCoin  =" + (life.goldCoin - _count) + " where id = " + life.id;
                    MySqlExecuteTools.AddOrUpdate(sql);
                }
              
            }

            return "0";
        }

    }

         
}
